<?php
namespace Plu\Library\Services\Utility;

use Plu\Library\Services\ServiceBase;

class UrlService extends ServiceBase {
    /**
     * 自动生成链接
     * @param params 参数
     * @param uri    基本url
     * @param igoreOld 是否屏蔽老的
     * @param extraValues 额外值，将自动合并到params
     */
    public static function createUrl($params, $url = '', $igoreOld = false,  $extraValues = array()) {
        if (!empty($extraValues)) {
            for ($c = 0, $len = count($extraValues); $c < $len; $c++) {
                list($k, $v) = $extraValues[$c];
                $params[$k] = $v;
            }
        }

        if (!$url) {
            $url = self::getUrl();
        }

        $pos = strpos($url, '?');

        if ($pos === false) {
            $url .= '?'.http_build_query($params);
        } else {
            $querystring = substr(strstr($url, '?'), 1);
            $query_array = array();

            if (!$igoreOld) {
                parse_str($querystring, $pars);
                foreach ($pars as $k => $v) {
                    if ($k != 'page') {
                        $query_array[$k] = $v;
                    }
                }
            }
            foreach ($params as $k => $v) {
                $query_array[$k] = $v;
            }
            $querystring = http_build_query($query_array);//.'&'.$par;
            $url = substr($url, 0, $pos) . '?' . $querystring;
        }

        return $url;
    }

    public static function getUrl() {
        $di = self::_getDI();
        $request = $di->get('request');
        $scheme = $request->getScheme();
        $host = $request->getHttpHost();
        $uri  = $request->getURI();

        return $scheme."://".$host . $uri;
    }

    public static function domain($tlLength = 1) {
        $di = self::_getDI();
        $request = $di->get('request');

        $host = $request->getHttpHost();
        $segments = explode(".", $host);
        $domain = array_slice($segments, -1 * ($tlLength + 1));
        $domain = join(".", $domain);

        return $domain;
    }
}
?>
